#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

#@PydevCodeAnalysisIgnore
import cgi
from django.utils import simplejson
from google.appengine.api import channel, memcache, users, users
from google.appengine.ext import db, db, webapp, webapp
from google.appengine.ext.webapp import util, template
from google.appengine.ext.webapp.util import run_wsgi_app
import datetime
import os
import uuid
import urllib2
import urllib
import logging
from django.utils import simplejson as json
from distutils.log import INFO
from django.http import HttpResponse
from cgi import log
from Queue import Empty
from pickle import NONE

def getJST(time):
    return time + datetime.timedelta(hours=9)

class TimeSale(db.Model):
    title = db.StringProperty(multiline=False)
    startTime = db.StringProperty(multiline=False)
    endTime = db.StringProperty(multiline=False)
    pushTime = db.StringProperty(multiline=False)
    url = db.StringProperty(multiline=False)
    content = db.StringProperty(multiline=True)
    shopId = db.StringProperty(multiline=True)
    sentFlg = db.StringProperty(multiline=True)

class Profile(db.Model):
    age = db.StringProperty(multiline=False)
    sex = db.StringProperty(multiline=False)
    job = db.StringProperty(multiline=False)
    shopId = db.StringProperty(multiline=False)
    receive = db.StringProperty(multiline=False)
#    color = db.StringProperty(multiline=False)

class ShopInfo(db.Model):
    shopId = db.StringProperty(multiline=False)
    name = db.StringProperty(multiline=False)
    zipCode = db.StringProperty(multiline=False)
    pref = db.StringProperty(multiline=False)
    city = db.StringProperty(multiline=False)
    banch = db.StringProperty(multiline=False)
    building = db.StringProperty(multiline=False)
    tel = db.StringProperty(multiline=False)
    fax = db.StringProperty(multiline=False)
    password = db.StringProperty(multiline=False)

class Session(db.Model):
    id = db.StringProperty(required = True)
    shopId = db.StringProperty(required = True)
    ip = db.StringProperty()

class loginForm(webapp.RequestHandler):
    def get(self):
        
        logging.debug("ログイン画面表示")
        
        values = {
            'html': "",
        }
        path = os.path.join(os.path.dirname(__file__), 'tmpl/login.html')
        self.response.out.write(template.render(path, values))

class login(webapp.RequestHandler):
    #パスワードはmd5でダイジェストし、Base64でエンコードする
    def post(self):
        shopList = db.GqlQuery("SELECT * FROM ShopInfo where shopId = :1",self.request.get('shopId'))
        
        if shopList.count > 0:
        
            logging.debug("該当ショップあり")
            
            for shop in shopList:
                if shop.password == self.request.get('password'):

                    logging.debug("ログイン成功")

                    #ログイン成功したとき、uuidでアプリで唯一らしき意味のないランダムな文字列を生成し、これをセッションIDとする。なお、HTTPのアクセス元IPアドレスとセットにする
                    session = Session(id = str(uuid.uuid4()), shopId=shop.shopId,ip=self.request.remote_addr)
                    session.put()
                    #HTTPヘッダにクッキー情報を追加する。セッションIDと有効期限、有効なパスを設定する
                    self.response.headers.add_header(
                        "Set-Cookie",
                        "sessionid=%s; expires=Fri, 31-Dec-2020 23:59:59 GMT; path=/" % session.id
                    )
                self.response.setparams()
                self.redirect("/infolist?sessionid=" + session.id)
                return
            
        logging.debug("ログイン失敗")
        self.redirect("/loginForm")

def auth(sessionId):
    
    sessionList = db.GqlQuery("SELECT * FROM Session where id = :1",sessionId)
    
    result = ''
    
    if sessionList.count > 0:
        for session in sessionList:
            result = session.shopId
            
    return result

class shopRegist(webapp.RequestHandler):
    def get(self):
        
        logging.debug("ショップ登録画面表示")
        
        values = {
            'html': "",
        }
        path = os.path.join(os.path.dirname(__file__), 'tmpl/shopRegist.html')
        self.response.out.write(template.render(path, values))


class shopInsert(webapp.RequestHandler):
    def post(self):
        
        logging.debug("ショップ登録処理")
        
        shopInfo = ShopInfo(key_name=self.request.get('shopId'))

        shopInfo.name = self.request.get('name')
        shopInfo.zipCode = self.request.get('zipCode')
        shopInfo.prefectures = self.request.get('prefectures')
        shopInfo.municipality = self.request.get('municipality')
        shopInfo.banch = self.request.get('banch')
        shopInfo.building = self.request.get('building')
        shopInfo.tel = self.request.get('tel')
        shopInfo.fax = self.request.get('fax')
        shopInfo.password = self.request.get('password')
        shopInfo.shopId = self.request.get('shopId')

        logging.info("ショップ登録：" + str(self.request.get('shopId')))

        shopInfo.put()
        self.redirect('/infolist')

class Regist(webapp.RequestHandler):
    def get(self):
        
        

        logging.debug("タイムセール登録画面表示")

        values = {
            'html': "",
        }
        path = os.path.join(os.path.dirname(__file__), 'tmpl/infoRegist.html')
        self.response.out.write(template.render(path, values))

class infoInsert(webapp.RequestHandler):
    def post(self):

        logging.debug("タイムセール登録処理")
        
        timeSale = TimeSale()

        timeSale.title = self.request.get('title')
        timeSale.startTime = self.request.get('startYear') + self.request.get('startMonth') +  self.request.get('startDay') + self.request.get('startHour')+ self.request.get('startMinutes')
        timeSale.endTime = self.request.get('endYear') +self.request.get('endMonth') + self.request.get('endDay') + self.request.get('endHour')+ self.request.get('endMinutes')
        timeSale.pushTime = self.request.get('pushYear') +self.request.get('pushMonth') + self.request.get('pushDay') + self.request.get('pushHour')+ self.request.get('pushMinutes')
        timeSale.url = self.request.get('url')
        timeSale.content = self.request.get('content')
        timeSale.shopId = "1"
        timeSale.sentFlg = "0"
        timeSale.put()
        
        logging.info("タイムセール登録：" + cgi.escape(timeSale.title.encode('utf-8')))
        
        self.redirect('/infolist')

class profileRegist(webapp.RequestHandler):
    def get(self):

        logging.debug("プロフィール登録画面表示")
        
        shopList = db.GqlQuery("SELECT * FROM ShopInfo ")
        shopHtml = ""

        profileList = db.GqlQuery("SELECT * FROM Profile ")

        for profile in profileList:

            profileList += '<div>'
            profileList += '    <p class="select">'
            profileList += '        ★年齢<br>'
            profileList += '        <select name="age">'
            profileList += '            <option value="">'
            profileList += '            <option value="10歳未満">10歳未満'
            profileList += '            <option value="10代">10代'
            profileList += '            <option value="20代">20代'
            profileList += '            <option value="30代">30代'
            profileList += '            <option value="40代">40代'
            profileList += '            <option value="50代">50代'
            profileList += '            <option value="60代">60代'
            profileList += '            <option value="70代">70代'
            profileList += '            <option value="80代">80代'
            profileList += '           <option value="90歳以上">90歳以上'
            profileList += '        </select>'
            profileList += '    </p>'
            profileList += '    <p class="select">'
    
            profileList += '        ★性別<br>'
            profileList += '<div>'
            profileList += ' <dl class="ColorRadio" id="rdoSex">'
            profileList += '<dd>'
            profileList += '  <ul>'
            profileList += '    <li><input type="radio" name="sex" value="man" id="man" /><label for="man">男性</label></li>'
            profileList += '    <li><input type="radio" name="sex" value="woman" id="woman" /><label for="woman">女性</label></li>'
            profileList += '  </ul>'
            profileList += '</dd>'
            profileList += '</dl>'
            profileList += '</div>'
            profileList += '    </p>'
    
    
            profileList += '    <p class="select" style="clear: both; padding-top: 35px;">'
            profileList += '        ★職業<br>'
            profileList += '        <select name="job"><option value="">'
            profileList += '            <option value="学生">学生'
            profileList += '            <option value="会社員">会社員'
            profileList += '            <option value="自営業">自営業'
            profileList += '            <option value="主婦">主婦'
            profileList += '            <option value="パート・アルバイト">パート・アルバイト'
            profileList += '            <option value="なし">なし'
            profileList += '        </select>'
            profileList += '    </p>'
            profileList += '    <p class="select">'
            profileList += '        ★最寄りの店舗<br>'
            profileList += '        <select name="shopNo">'
            profileList += '            <option value="">'
            profileList += '            {{shopHtml}}'
            profileList += '        </select>'
            profileList += '    </p>'
            profileList += '    <p style="font-size: 1em; color: darkseagreen; padding-left: 44px;">'
            profileList += '       <INPUT type="checkbox" name="receive" value="1">&nbsp;近辺の店舗からも受け取る'
            profileList += '    </p>'
    
            profileList += '</div>'
            profileList += '<div>'
            profileList += '    <p class = "entry_more" >'
            profileList += '        <img src="/images/button.png" onclick="regist();">'
            profileList += '    </p>'
            profileList += '</div>'
            profileList += '<input type="hidden" name="regId" value="{{regId}}" />'
            profileList += '</form>'

        for shop in shopList:
            shopHtml = shopHtml + "<option value=%s>" % shop.key().id_or_name()
            shopHtml = shopHtml + "%s"  % cgi.escape(shop.name)
            shopHtml = shopHtml + "</option>"
            
        regId = self.request.get('regId')
        
        values = {
            'shopHtml': shopHtml,
            'regId' : regId
        }
        path = os.path.join(os.path.dirname(__file__), 'tmpl/profile.html')
        self.response.out.write(template.render(path, values))

class profileInsert(webapp.RequestHandler):
    def post(self):

        logging.debug("プロフィール登録処理")
        
        regId = self.request.get('regId')
        
        if regId == "":
            regId = "PC"

        profile = Profile(key_name=regId)

        profile.age = self.request.get('age')
        profile.sex = self.request.get('sex')
        profile.job = self.request.get('job')
        profile.shopId = self.request.get('shopId')
        profile.receive = self.request.get('receive')
#        profile.color = self.request.get('color')
        profile.put()

        logging.info("プロフィール登録：" + self.request.get('regId').encode('utf-8'))

        self.redirect('/')


class infoList(webapp.RequestHandler):
    def get(self):
#
        logging.debug("タイムセール一覧管理画面表示")

        timeSaleList = db.GqlQuery("SELECT * FROM TimeSale LIMIT 10 ")
        infoList = ''

        for timeSale in timeSaleList:

            infoList += '<tr >'
            infoList += '<td rowspan="3"><input type="radio" name="sale" value="sale" checked></td>'
            infoList += '<td>'
            infoList += '%s' % cgi.escape(timeSale.title.encode('utf-8'))
            infoList += '</td></tr>'
            infoList += '<tr><td>'
            infoList +=  '%s' % cgi.escape(str(timeSale.startTime).encode('utf-8'))
            infoList += '<tr><td>'
            infoList += '%s' % cgi.escape(timeSale.content.encode('utf-8'))
            infoList += '</td></tr>'
            
        values = {
            'html': infoList,
        }
        path = os.path.join(os.path.dirname(__file__), 'tmpl/infoList.html')
        self.response.out.write(template.render(path, values))

class list(webapp.RequestHandler):
    def get(self):

        logging.debug("タイムセール一覧画面表示")

        shopList = db.GqlQuery("SELECT * FROM ShopInfo ")
        shopHtml = ""

        currentTime = getJST(datetime.datetime.now()).strftime('%Y%m%d%H%M')


        timeSaleList = db.GqlQuery("SELECT * FROM TimeSale where startTime < :1 order by startTime desc LIMIT 5 ",currentTime)
        infoList = ''
        infoCount = 0
        
        for timeSale in timeSaleList:
            infoCount = infoCount + 1

            shopName = ''
            for shop in shopList:
                if shop.key().id_or_name() == timeSale.shopId:
                    shopName = shop.name
                    break
            
            
            time = str(timeSale.startTime)[4:6] + "/" + str(timeSale.startTime)[6:8] + " " + str(timeSale.startTime)[8:10]
            time = time + ":" + str(timeSale.startTime)[10:12] + "～" + str(timeSale.endTime)[8:10] +":" + str(timeSale.endTime)[10:12]
            
            infoList += '<table>'
            infoList += '    <tr>'
            infoList += '        <td style="padding-bottom: 20px;background-repeat:no-repeat;" width="100" background="/images/store.png" align="center"><div class="shopName">%s</td>' % cgi.escape(shopName.encode('utf-8'))                                    
            if timeSale.startTime <= currentTime and timeSale.endTime >= currentTime:
                infoList += '        <td width="5px"><img src="/images/hotIcon.png" class="hotIcon"></td>'
            else:
                infoList += '        <td width="5px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>'
            infoList += '        <td>'
            if infoCount % 2 == 1:
                infoList += '            <div id="textarea">' 
                infoList += '                <div class="textinner">'
            else:
                infoList += '            <div id="textarea2">' 
                infoList += '                <div class="textinner2">'                
            infoList += '                    <table>'
            infoList += '                        <tr>'
            infoList += '                            <td class="textDateTime">%s</td>' % time
            infoList += '                        </tr>'
            infoList += '                        <tr>'
            infoList += '                            <td class="textTitle">'
            infoList += '%s' % cgi.escape(timeSale.title.encode('utf-8'))
            infoList += '                            </td>' 
            infoList += '                        </tr>'
            infoList += '                        <tr>'
            infoList += '                            <td class="textHonbun">'
            infoList += '%s' % cgi.escape(timeSale.content.encode('utf-8'))
            infoList += '                                </td>'
            infoList += '                        </tr>'
            infoList += '                    </table>'
            infoList += '                </div><!--/textinner-->'
            if infoCount % 2 == 1:
                infoList += '                <div class="triangle">'
            else:
                infoList += '                <div class="triangle2">'                
            infoList += '            </div><!--/textarea-->'
            infoList += '        </td>'
            infoList += '    </tr>'
            infoList += '</table>'
            
        regId = self.request.get('regId')
        
        values = {
            'html': infoList,
            'regId' : regId
        }
        path = os.path.join(os.path.dirname(__file__), 'tmpl/list.html')
        self.response.out.write(template.render(path, values).decode('utf-8'))

class message(webapp.RequestHandler):
    def get(self):

        #バックエンドへのリリースは
        #appcfg.py backends "C:\Program Files (x86)\eclipse\workspace\ssspsystem" update

        logging.debug("ジョブ開始")

        now = getJST(datetime.datetime.now())

        timeSaleList = db.GqlQuery("SELECT *  FROM TimeSale where sentFlg = '0' and pushTime <= :1",now.strftime('%Y%m%d%H%M'))
        logging.debug("通知情報取得SQL：SELECT *  FROM TimeSale where sentFlg = '0' and pushTime <= " + now.strftime('%Y%m%d%H%M'));

        logging.debug("通知件数：" + str(timeSaleList.count()));
        
        response = None
        
        for timeSale in timeSaleList:


            regIds = []
            
            userList = db.GqlQuery("SELECT * FROM Profile where shopId = :1",timeSale.shopId.encode('utf-8'))
            logging.debug("ユーザー取得SQL：SELECT *  FROM Profile where shopId = " + timeSale.shopId.encode('utf-8'))

            logging.info("タイムセール通知：タイトル="  + cgi.escape(timeSale.title.encode('utf-8')) + "通知ユーザ数=" + str(userList.count()))
            
            if userList.count() > 0:
    
                for user in userList:
                    
                    regIds.append(user.key().id_or_name())
                    logging.debug(user.key().id_or_name())
                
                    json_data = {"collapse_key" : "TimeSale", "data" : 
                                 {
                                  "Title" : '%s' % cgi.escape(timeSale.title.encode('utf-8'))
                                  }
                                 , "registration_ids": regIds,
                    }
        
                    url = 'https://android.googleapis.com/gcm/send'
                    apiKey = "AIzaSyAn1hGeK3xgk782PJp087IzmuLyT4_Aw9Q"
                    myKey = "key=" + apiKey
                    headers = {'Content-Type': 'application/json', 'Authorization': myKey}
        
                    data = json.dumps(json_data)
                    req = urllib2.Request(url, data, headers)
                    f = urllib2.urlopen(req)
                    response = json.loads(f.read())
                    
                    timeSale.sentFlg = '1'
                    timeSale.put()

                logging.info(response);
        return;

class regid(webapp.RequestHandler):
    def get(self):

        logging.debug("新規ユーザID登録処理はスキップ中：regId="  + str(self.request.get('regId')))
        
        profile = Profile(key_name=self.request.get('regId'))

        profile.userID = self.request.get('regId')
        #profile.put()
    

def main():
    application = webapp.WSGIApplication([('/', list)
                                          , ('/infolist', infoList)
                                          , ('/infoInsert', infoInsert)
                                          , ('/shopRegist', shopRegist)
                                          , ('/shopInsert', shopInsert)
                                          , ('/profileRegist', profileRegist)
                                          , ('/profileInsert', profileInsert)
                                          , ('/list', list)
                                          , ('/message', message)
                                          , ('/loginForm', loginForm)
                                          , ('/login', login)
                                          , ('/regid', regid)
                                          , ('/regist', Regist)]
                                         , debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()

